<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar
      style="color: #fff"
      title="个人主页"
      @click-left="$router.back()"
      left-arrow
    />
    <div class="container">
      <input
        type="file"
        hidden
        id="file"
        accept="image/*"
        ref="file"
        @change="change"
      />
      <!-- /导航栏 -->
      <van-cell title="头像" center>
        <!-- 点击label标签也会触发for 的点击 -->
        <label for="file">
          <van-image
            width="50"
            height="50"
            round
            fit="cover"
            :src="list.avatar"
          />
        </label>
      </van-cell>

      <van-cell
        title="昵称"
        is-link
        @click="showDialog"
        v-model="list.nickname"
      ></van-cell>

      <van-cell title="性别" is-link @click="sexPickerShow1" :value="list.sex">
      </van-cell
      ><van-popup v-model="sexPickerShow" position="bottom"
        ><van-picker
          show-toolbar
          :columns="columns"
          @confirm="sexPickerConfirm"
          @cancel="sexPickerShow = false"
      /></van-popup>
      <!-- 日期选择 -->
      <van-cell
        title="生日"
        is-link
        @click="dataPickerShow = true"
        v-model="list.birthday"
      ></van-cell>
      <van-popup v-model="dataPickerShow" position="bottom"
        ><van-datetime-picker
          v-model="list.birthday"
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="dataPickerConfirm"
          @cancel="dataPickerShow = false"
      /></van-popup>
      <div style="margin: 30px 50px" @click="shangchuan">
        <van-button
          round
          block
          type="primary"
          size="normal"
          :square="true"
          native-type="submit"
          >确定</van-button
        >
      </div>
    </div>
    <van-dialog v-model="nickDialogShow" title="修改昵称" show-cancel-button>
      <input type="text" v-model="list.nickname" />
    </van-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
      columns: ["男", "女"],
      show: false,
      sexPickerShow: false,
      dataPickerShow: false,
      nickDialogShow: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      uid: "",
    };
  },
  mounted() {
    this.uid = localStorage.getItem("uid");
    this.token = localStorage.getItem("token");
    console.log(this.uid);
    this.upload();
  },
  methods: {
    // 性别选择器确定事件
    sexPickerConfirm(e) {
      console.log(e);
      this.list.sex = e;
      console.log(this.sexPickerShow);
      this.sexPickerShow = false;
    },
    dataPickerConfirm(e) {
      console.log(e); //日期对象
      let year = e.getFullYear();
      let month = e.getMonth() + 1;
      let date = e.getDate();
      let d = [year, month, date]
        .map((v) => {
          return (v + "").length > 1 ? v : "0" + v;
        })
        .join("/");
      this.list.birthday = d;
      this.dataPickerShow = false;
    },
    sexPickerShow1() {
      this.sexPickerShow = true;
    },
    // 上传图片
    async upload2(fileList) {
      // 1.判断一下选图片了没
      let imageSrc = [];
      if (!fileList || fileList.length == 0) {
        return imageSrc;
      }
      // 多个异步任务都执行完成 返回他们完成后的结过
      let task = fileList.map((v) => {
        return new Promise(async (resolve, reject) => {
          let { file } = v;

          let { type } = file;

          //  拿到类型  比如jpg
          type = type.split("/")[1];
          // 重新命名  随机名字
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          // 去服务器申请一个上传token

          let {
            data: { token },
          } = await this.axios.get("/upload/token");
          console.log(token);
          const formdata = new FormData();
          formdata.append("file", file);
          formdata.append("token", token);
          formdata.append("key", file_name);

          // 向七牛云请求
          this.axios
            .post("https://upload-z1.qiniup.com", formdata)
            .then((res) => {
              console.log(res);
              resolve(`http://toutiao.longxiaokj.com/` + res.data.key);
            });
        });
      });
      imageSrc = await Promise.all(task);
      console.log(imageSrc);
      return imageSrc;
    },
    upload() {
      this.axios
        .post("/user/getuserInfo", { token: this.token })
        .then((res) => {
          console.log(res);
          this.list = res.data.userInfo;
          console.log(this.list);
        });
    },
    async shangchuan() {
      let { nickname, avatar, file, sex, birthday } = this.list;

      if (file) {
        // 证明咱们上传头像
        let fileList = [
          {
            file,
          },
        ]; //和vant上传组件形状一样

        let res = await this.upload2(fileList);
        avatar = res[0];
        console.log(avatar);
      }

      this.axios
        .post("/user/editUserInfo", {
          avatar: avatar,
          nickname: nickname,
          sex: sex,
          birthday: birthday,
          uid: this.uid,
        })
        .then((res) => {
          console.log(res);
          this.upload();
          this.$toast("修改成功");
          setTimeout((v) => {
            this.$router.push("/my");
          }, 500);
        });
    },
    showDialog() {
      this.nickDialogShow = true;
    },
    change(e) {
      console.log(e.target.files);
      let file = e.target.files[0];

      // 1.前端预览
      this.list.file = file;
      let fileReader = new FileReader();

      fileReader.readAsDataURL(file);

      fileReader.onload = (e) => {
        this.list.avatar = e.target.result;
      };

      console.log(this.list);
    },
  },
};
</script>

<style scoped lang="scss">
.van-popup {
  background-color: #f5f7f9;
}
.van-nav-bar {
  background-color: #07c160;
}
.update-photo-popup {
  background-color: #000;
}

.name-field-wrap {
  padding: 10px;
}
.update-photo {
  height: 100%;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}

/* Ensure the size of the image fit the container perfectly */
.image {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
.van-dialog {
  input {
    margin: 15px 0;
    text-align: center;
    width: 100%;
    border: none;
  }
}
</style>
